-- This class defines the Finite State Machine control
-- March 3, 2007

LIBRARY ieee;
USE ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;

ENTITY MII IS
	PORT
	(	Clock							: IN	STD_LOGIC;
		Q								: OUT	STD_LOGIC_VECTOR(3 DOWNTO 0);
        Reset						    : IN	STD_LOGIC;
		TX_EN							: IN	STD_LOGIC;
		TXD								: OUT	STD_LOGIC_VECTOR(3 DOWNTO 0);
		FSM_MIIDATA						: IN	STD_LOGIC_VECTOR(3 DOWNTO 0);
		buffer_busy 					: IN	STD_LOGIC;
		buffer_empty					: IN	STD_LOGIC;
		FSM_GetNext					    : OUT	STD_LOGIC;
		--FIN_FRAME                       : OUT	STD_LOGIC;
		CLR								: OUT	STD_LOGIC);
END MII;

ARCHITECTURE Behavior OF MII IS
	TYPE State_type IS (RESET_state, fPROBE,dataREQUEST);
	SIGNAL state: State_type;
	SIGNAL tmp: STD_LOGIC_VECTOR(3 DOWNTO 0);
BEGIN
	PROCESS (Reset,Clock)
	BEGIN
		IF Reset = '1' THEN 
			state <= RESET_state;
		ELSIF Clock'EVENT AND Clock = '1' THEN
			CASE state IS
				WHEN RESET_state => -- Reset State
						IF buffer_empty = '1' THEN
						state <= RESET_state;
						ELSE	
						state <= fPROBE;
						END IF;
				WHEN fPROBE => -- State for probing buffer to see if full and frame is complete.
					IF   buffer_busy = '0' THEN
						FSM_GetNext <= '1';
						
						state <= dataREQUEST;
					ELSE
						state <= fPROBE;
					END IF;
				WHEN dataREQUEST => 
					IF TX_EN = '0' THEN
					CLR <= '1';
					state <= fPROBE;
					tmp <= "0000"; 
          		ELSIF state = dataREQUEST AND TX_EN='1' THEN
           			 tmp <= tmp + 1;
				END IF;
			--IF Q => '1100' THEN
			 --FIN_FRAME <= '1';
			--ELSE
				--FIN_FRAME <= '0';
			--END IF;
			END CASE;
		END IF;
	END PROCESS;
	TXD <= FSM_MIIDATA WHEN (state = dataREQUEST AND TX_EN = '1');
    Q <= tmp; 

END Behavior;
